// DatastoreItems.cpp : Implementation of CDatastoreItems

#include "stdafx.h"
#include "DatastoreItems.h"
#include "DatastoreItem.h"

// CDatastoreItems

STDMETHODIMP CDatastoreItems::InterfaceSupportsErrorInfo(REFIID riid)
{
	static const IID* arr[] = 
	{
		&IID_IDatastoreItems
	};

	for (int i=0; i < sizeof(arr) / sizeof(arr[0]); i++)
	{
		if (InlineIsEqualGUID(*arr[i],riid))
			return S_OK;
	}
	return S_FALSE;
}

STDMETHODIMP CDatastoreItems::get__NewEnum(IUnknown** pVal)
{
    return this->QueryInterface(__uuidof(IUnknown), (void **)pVal);
}

STDMETHODIMP CDatastoreItems::get_Count(LONG* pVal)
{
	*pVal = (LONG)m_Ids.size();
	return S_OK;
}

STDMETHODIMP CDatastoreItems::get_Item(LONG Index, IDatastoreItem** pVal)
{
	CComObject<CDatastoreItem> * pItem = GetComObject<CDatastoreItem>();
	pItem->m_Id = m_Ids[Index];
	pItem->m_Type = m_Type;
	*pVal = pItem;
	return S_OK;
}

STDMETHODIMP CDatastoreItems::Next(ULONG celt, VARIANT *rgVar, ULONG *pCeltFetched)
{
    if (pCeltFetched != NULL)
	{
		*pCeltFetched = 0;
	}
	
	LONG size;
	get_Count(&size);
	
	for(ULONG i = 0; i < celt; i++)
	{
		if (m_Cur > size)
		{
			return S_FALSE;
		}

		IDatastoreItem * pItem;
		get_Item(m_Cur, &pItem);
		rgVar[i] = _variant_t(pItem).Detach();

		Skip(1);

		if (pCeltFetched != NULL)
		{
			(*pCeltFetched)++;
		}		
	}
	return S_OK;
}

STDMETHODIMP CDatastoreItems::Skip(ULONG celt)
{
    m_Cur += celt;
    return S_OK;
}

STDMETHODIMP CDatastoreItems::Reset(void)
{
    m_Cur = 0;
    return S_OK;
}

STDMETHODIMP CDatastoreItems::Clone(IEnumVARIANT **ppEnum)
{	
    CComObject<CDatastoreItems> * pItems = GetComObject<CDatastoreItems>();
	*pItems = this;
    *ppEnum = (IEnumVARIANT *)pItems;
	return S_OK;
}


STDMETHODIMP CDatastoreItems::get_Type(TsDatastoreItemTypeEnum* pVal)
{
	*pVal = m_Type;
	return S_OK;
}

HRESULT CDatastoreItems::Init(CDatastore * pDs, TsDatastoreItemTypeEnum type)
{
	m_pDs = pDs;
	m_Type = type;
	return S_OK;
}
